package com.easybuilder.common.utils;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ServletUtil {

    public static void writeJSON(HttpServletResponse response, Object data) {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        try {
            response.getWriter().write(data.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /** 设置token */
    public static void setToken(String token) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes  = (ServletRequestAttributes) requestAttributes;
        HttpServletResponse response = attributes.getResponse();
        response.setHeader("Authorization", token);
        response.setHeader("Access-Control-Expose-Headers","Authorization");

    }
}
